Dictionaries in Python
Dictionaries, also known as associative arrays in other languages, are fundamental data structures in Python. They store collections of key-value pairs, providing a flexible way to organize and access data.
Key Concepts:
⯁
Keys: Unique and immutable (unchangeable) values used to identify elements within the dictionary. Keys can be strings, numbers, tuples, or even custom objects (as long as they are hashable, meaning they can be uniquely identified for efficient lookups).
⯁
Values: The actual data associated with each key. Values can be of any data type (numbers, strings, lists, dictionaries, etc.).
⯁
Key-Value Pairs: Each entry in a dictionary is a key-value pair, where the key acts as a label and the value is the corresponding data.
Creating Dictionaries:
Here are several ways to create dictionaries in Python:
1. Curly Braces {} (Most Common)
Enclose key-value pairs within curly braces, separated by commas and colons separating keys and values.
Creating dictionaries using curly braces {} in python
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)
print(type(my_dict))
Output
{'name': 'Alice', 'age': 30, 'city': 'New York'}
2. dict() Constructor:
The dict() constructor can be used to create dictionaries from various iterables (lists, tuples) or key-value pairs.
Create dictionary using dict() constructor in python
# From a list of key-value pairs
my_list = [("name", "Bob"), ("age", 25)]
my_dict = dict(my_list)
print(my_dict)
# From a sequence of key-value tuples
my_tuple = ("name", "Charlie"), ("age", 42)
my_dict = dict(my_tuple)
print(my_dict)
Output
{'name': 'Bob', 'age': 25}
{'name': 'Charlie', 'age': 42}
3. dict.fromkeys() Method
Creates a dictionary with specified keys and a default value for all keys.
create dictionary using dict.fromkeys() method in python
keys = ("x", "y", "z")
default_value = 0
my_dict = dict.fromkeys(keys, default_value)
print(my_dict)
Output
{'x': 0, 'y': 0, 'z': 0}
4. Comprehension (Advanced)
For complex dictionary creation logic, use dictionary comprehensions
Create dictionary using dict comprehension(adv) in python
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Let's discuss about accessing dictionaries in python in next tutorial.